const { Service } = require('dx-router-admin');
const orderEntity = require('../entity/order.js');

module.exports = class Order extends Service {
	constructor(ctx) {
		super(ctx);
		this.entity = orderEntity;
	}
	getOrderSn() {
		const date = new Date();
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		const day = date.getDate();
		const hours = date.getHours();
		const minutes = date.getMinutes();
		const seconds = date.getSeconds();
		const milliSeconds = date.getMilliseconds();
		const random = this.$dx.utils.random(1, 9999);
		return `${year}${month.toString().padStart(2, '0')}${day.toString().padStart(2, '0')}${hours.toString().padStart(2, '0')}${minutes
			.toString()
			.padStart(2, '0')}${seconds.toString().padStart(2, '0')}${milliSeconds.toString().padStart(4, '0')}${random.toString().padStart(4, '0')}`;
	}
	async settlement({ outTradeNo, totalFee, transactionId }) {
		const order = await this.where('order_sn', outTradeNo).where('status', 0).find();
		if (!order) {
			return this.$dx.fail('订单不存在');
		}
		if (order.amount * 100 != totalFee) {
			return this.$dx.fail('订单金额不一致');
		}
		await this.where('_id', order._id).update({
			status: 1,
			transaction_id: transactionId,
			paytime: Date.now(),
		});
		// VIP记录
		await this.$dx.service.logs.addDate(order);
		return true;
	}
	user() {
		return this.hasOne('uni-id-users', 'user_id', '_id').field(['nickname', 'avatar']);
	}
};
